package com.yysoft.core.web.controller;

import com.yysoft.core.model.SysUser;
import com.yysoft.core.service.IUserService;
import com.yysoft.core.utils.EntryptUtil;
import com.yysoft.core.utils.UserSessionUtils;
import com.yysoft.core.utils.annotation.AuthUser;
import com.yysoft.core.web.BaseController;
import com.yysoft.core.web.model.AjaxResponse;
import com.yysoft.core.web.model.MenuModel;
import com.yysoft.core.web.model.YYException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
public class SysController extends BaseController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/login")
    public AjaxResponse login(HttpServletRequest request, String username, String password) throws Exception {
        AjaxResponse ajaxResponse = new AjaxResponse();
        SysUser user = userService.findByUsername(username);
        boolean flag = false;
        if(user == null){
            flag = true;
        } else if(!EntryptUtil.validatePassword(password, user.getPassword())){
            flag = true;
        }
        if(flag)
            throw new YYException("用户名不存在或密码错误");
        UserSessionUtils.setUserSession(request, user);
        ajaxResponse.setData(user);
        return ajaxResponse;
    }

    @RequestMapping("/sys/getMenuList")
    @AuthUser
    public AjaxResponse getMenuList(@AuthUser SysUser user) throws Exception {
        AjaxResponse ajaxResponse = new AjaxResponse();

        List<MenuModel> menuList = new ArrayList<>();
        menuList.addAll(userService.getMenuList(user.getUserId(), "inner", null));

        ajaxResponse.setData(menuList);
        return ajaxResponse;
    }

    @RequestMapping("/logout")
    @AuthUser
    public AjaxResponse logout(HttpServletRequest request) throws Exception {
        UserSessionUtils.removeUserSession(request);
        return new AjaxResponse();
    }

}
